<?php
/**
 *
 * Description:一条url
 * Author: falcon
 * Date: 18/5/11
 * Time: 下午4:10
 *
 */

ignore_user_abort(true);
require_once __DIR__ . '/config.php';
session_write_close();

$accessToken = file_get_contents(__DIR__ . '/accesstoken.txt');
$today = date('Ymd');
$data_file = __DIR__ . '/data/' . $today . '.txt';
$log_file = __DIR__ . '/logs/'.$today.'.txt';

if(empty(@$_GET['link'])) {
    exit('bad_request');
}else{
    $link = urldecode($_GET['link']);
	echo 'ok';
}

if(function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
    $time_limit = 8;
}else{
    $time_limit = 1;
}


for($i=0;$i<$time_limit;$i++) {

    $data_urls = !is_file($data_file) ? '' : file_get_contents( $data_file );

    $link = str_replace(array("\r",'\n'),'',$link);
    if(strpos($data_urls,$link) !== false) {
        echo $log = sprintf("API [%s] : ignore   %s\n", date("Y-m-d H:i:s"), $link);
        file_put_contents($log_file, $log."\n", FILE_APPEND);
        break;
    }

    $error = false;

    try {
        // Get the \Facebook\GraphNodes\GraphUser object for the current user.
        // If you provided a 'default_access_token', the '{access-token}' is optional.
        $response = $fb->post('/?scrape=true&id=' . urlencode($link), [], $accessToken);
    } catch (\Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error

        $error = 'Graph returned an error: ' . $e->getMessage();
        //exit;
    } catch (\Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        $error = 'Facebook SDK returned an error: ' . $e->getMessage();
        //exit;
    }

    echo $log = sprintf("API push: [%s] %s : %s\n", date("Y-m-d H:i:s"), $link, ($error!==false) ? $error : 'OK');

    file_put_contents($log_file, $log."\n", FILE_APPEND);

    if (!$error) {
        file_put_contents($data_file, $link."\n", FILE_APPEND);
    }

}
